<template>
  <div class="newsList" ref="newsList">
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
       <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell
        v-for="(item, index) in newList"
        :key="index"
        :title="item.title"
        @click="toDetail(item.art_id)"
      >
        <template #label>
          <!-- 图片区域 -->
          <van-grid
            v-if="item.cover.type !== 0"
            :border="false"
            :column-num="3"
          >
            <van-grid-item
              v-for="(subitem, subindex) in item.cover.images"
              :key="subindex"
            >
              <van-image :src="subitem" />
            </van-grid-item>
          </van-grid>
          <!-- 文章详情 -->
          <div class="detail">
            <span>{{ item.aut_name }}</span>
            <span>{{ item.comm_count }}</span>
            <span>{{ item.pubdate | timefromnow }}</span>
            <van-icon class="myicon" name="cross" />
          </div>
        </template>
      </van-cell>
    </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getNewListApi } from "@/api";
export default {
  props: ["channel_id"],
  data() {
    return {
      newList: [],
      loading: false,
      finished: false,
      timestamp: Date.now(),
      isLoading: false,
      // 保存滚动条距离
      scrollTop: 0,
    };
  },
  methods: {
    async onLoad() {
      if (this.isLoading) {
          this.newList = [];
          this.timestamp = Date.now()
          setTimeout(() => {
            this.isLoading = false;
          }, 2000)
        }
      const res = await getNewListApi({
        channel_id: this.channel_id,
        timestamp: this.timestamp,
      });
      this.newList = [...this.newList, ...res.data.data.results];
      this.timestamp = res.data.data.pre_timestamp;
      this.loading = false;
      // 判断是否还有后续数据
      if (this.timestamp === null) {
        // 将 list 设置为数据源加载完毕的状态
        this.finished = true;
      }
    },
    onRefresh() {
      // 清空列表数据
      this.finished = false;

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.onLoad();
    },
    // 跳转到详情页面
    toDetail(art_id) {
      this.$router.push(`/home/detail?id=${art_id}`);
    },
  },
  mounted() {
    // 给dom盒子加滚动事件
    this.$refs.newsList.onscroll = () => {
      this.scrollTop = this.$refs.newsList.scrollTop;
      // console.log(this.$refs.newsList.scrollTop);
    };
  },
  activated() {
    // 激活时再把之前的滚动条的高度赋值给滚动条，让它滚到对应的位置
    this.$refs.newsList.scrollTop = this.scrollTop;
  },
};
</script>

<style lang="less">
.newsList {
  position: fixed;
  top: 90px;
  bottom: 50px;
  left: 0;
  width: 100%;
  // background: red;
  overflow: auto;
  .detail {
    span {
      margin-right: 10px;
    }
    .myicon {
      float: right;
      color: #999;
    }
  }
}
</style>